package com.sproutcat.sample;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class SynchronizedExample1 {
   static class MyTask1 {
        public void func1() {
            synchronized (this) {
                for (int i = 0; i < 10; i++) {
                    System.out.print(i + " ");
                }
            }
        }
    }

    static class MyTask2 {

        private Lock lock = new ReentrantLock();

        public void func1() {
            lock.lock();
            try {
                for (int i = 0; i < 10; i++) {
                    System.out.print(i + " ");
                }
            } finally {
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) {
        MyTask2 e1 = new MyTask2();
        MyTask2 e2 = new MyTask2();
        ExecutorService executorService = Executors.newCachedThreadPool();
        executorService.execute(e1::func1);
        executorService.execute(e2::func1);
        executorService.shutdown();
    }

}
